package com.et.machine.manager.api;

import androidx.annotation.IntDef;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import kotlin.annotation.AnnotationRetention;
import kotlin.annotation.Retention;

final class SerialNumberUtil {
    private static final Random random = new Random();
    private static final Map<Integer, Object> map = new HashMap<>();

    @Retention(AnnotationRetention.SOURCE)
    @IntDef({SerialType.VMC, SerialType.TTO, SerialType.TEST, SerialType.UNSET})
    public @interface SerialType {
        int VMC = 0x00;
        int TTO = 0x01;
        int TEST = 0x02;
        int UNSET = 0x03;
    }

    static int getSerial(@SerialType int type) {
        int flow = random.nextInt(999999);
        flow = flow & 0xfffffffc | type;
        if (type == SerialType.TEST) {
            return flow;
        }
        for (int i = 0; i < 100; i++) {
            if (!map.containsKey(flow)) {
                map.put(flow, null);
                return flow;
            }
            flow = random.nextInt(999999);
            flow = flow & 0xfffffffc | type;
        }
        return -1;
    }

    @SerialType
    static int getTypeByLastByte(byte lastByte) {
        int b = Byte.parseByte(String.valueOf(lastByte), 10);
        switch (b & 0x3) {
            case SerialType.TEST:
                return SerialType.TEST;
            case SerialType.VMC:
                return SerialType.VMC;
            case SerialType.TTO:
                return SerialType.TTO;
            default:
                return SerialType.UNSET;
        }
    }
}
